/*
 * Copyright 2002-2018 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.aop.framework.autoproxy;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.aop.Advisor;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.BeanCurrentlyInCreationException;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;

/**
 * Helper for retrieving standard Spring Advisors from a BeanFactory,
 * for use with auto-proxying.
 *
 * @author Juergen Hoeller
 * @since 2.0.2
 * @see AbstractAdvisorAutoProxyCreator
 */
public class BeanFactoryAdvisorRetrievalHelper {

	private static final Log logger = LogFactory.getLog(BeanFactoryAdvisorRetrievalHelper.class);

	private final ConfigurableListableBeanFactory beanFactory;

	@Nullable
	private volatile String[] cachedAdvisorBeanNames;


	/**
	 * Create a new BeanFactoryAdvisorRetrievalHelper for the given BeanFactory.
	 * @param beanFactory the ListableBeanFactory to scan
	 */
	public BeanFactoryAdvisorRetrievalHelper(ConfigurableListableBeanFactory beanFactory) {
		Assert.notNull(beanFactory, "ListableBeanFactory must not be null");
		this.beanFactory = beanFactory;
	}


	/**
	 * Find all eligible Advisor beans in the current bean factory,
	 * ignoring FactoryBeans and excluding beans that are currently in creation.
	 * @return the list of {@link org.springframework.aop.Advisor} beans
	 * @see #isEligibleBean
	 */
	/**
	 * 在当前bean工厂中查找所有符合条件的Advisor类型bean，
	 * 会忽略FactoryBeans并排除当前正在创建中的bean。
	 *
	 * 执行流程：
	 * 1. 优先从缓存获取Advisor名称列表，避免重复查找
	 * 2. 若缓存未命中，则通过类型匹配获取所有Advisor类型的bean名称
	 * 3. 遍历名称列表，筛选出符合条件的bean（通过isEligibleBean判断）
	 * 4. 跳过当前正在创建中的bean，防止循环依赖问题
	 * 5. 将符合条件的Advisor bean实例化并添加到结果列表
	 *
	 * 此方法是Spring AOP自动代理机制的核心环节，
	 * 用于发现和收集系统中所有可用的切面增强器。
	 *
	 * @return 符合条件的Advisor bean列表
	 * @see #isEligibleBean - 判断bean是否符合自动代理条件
	 */
	public List<Advisor> findAdvisorBeans() {
		// 从缓存获取Advisor bean名称列表，避免重复扫描bean定义
		String[] advisorNames = this.cachedAdvisorBeanNames;
		if (advisorNames == null) {
			// 若缓存未命中，则通过类型匹配获取所有Advisor类型的bean名称
			// 注意：此处设置allowEagerInit为false，避免初始化FactoryBeans
			// 确保普通bean保持未初始化状态，以便后续自动代理处理器应用到它们
			advisorNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
					this.beanFactory, Advisor.class, true, false);
			// 将获取到的bean名称列表存入缓存
			this.cachedAdvisorBeanNames = advisorNames;
		}

		// 若没有找到任何Advisor bean，直接返回空列表
		if (advisorNames.length == 0) {
			return new ArrayList<>();
		}

		List<Advisor> advisors = new ArrayList<>();
		for (String name : advisorNames) {
			// 检查该bean是否符合自动代理条件（由子类实现具体逻辑）
			if (isEligibleBean(name)) {
				// 检查该bean是否正在创建中（处理循环依赖场景）
				if (this.beanFactory.isCurrentlyInCreation(name)) {
					if (logger.isTraceEnabled()) {
						logger.trace("Skipping currently created advisor '" + name + "'");
					}
				}
				else {
					try {
						// 通过bean工厂获取Advisor实例并添加到结果列表
						advisors.add(this.beanFactory.getBean(name, Advisor.class));
					}
					catch (BeanCreationException ex) {
						// 处理创建异常，检查是否由循环依赖引起
						Throwable rootCause = ex.getMostSpecificCause();
						if (rootCause instanceof BeanCurrentlyInCreationException) {
							BeanCreationException bce = (BeanCreationException) rootCause;
							String bceBeanName = bce.getBeanName();
							// 若异常由正在创建的bean依赖引起，则跳过当前Advisor
							if (bceBeanName != null && this.beanFactory.isCurrentlyInCreation(bceBeanName)) {
								if (logger.isTraceEnabled()) {
									logger.trace("Skipping advisor '" + name +
											"' with dependency on currently created bean: " + ex.getMessage());
								}
								// 忽略该异常，继续处理其他Advisor
								continue;
							}
						}
						// 若异常非循环依赖引起，则重新抛出
						throw ex;
					}
				}
			}
		}
		return advisors;
	}
	/**
	 * Determine whether the aspect bean with the given name is eligible.
	 * <p>The default implementation always returns {@code true}.
	 * @param beanName the name of the aspect bean
	 * @return whether the bean is eligible
	 */
	protected boolean isEligibleBean(String beanName) {
		return true;
	}

}
